package com.example.livehome

import android.content.IntentFilter
import android.media.AudioFormat
import android.net.ConnectivityManager
import android.os.Bundle
import android.view.SurfaceView
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.example.livehome.webrtc.WebRtcClient
import com.frank.live.LiveApplication
import com.frank.live.LivePusherNew
import com.frank.live.camera2.Camera2Helper
import com.frank.live.listener.LiveStateChangeListener
import com.frank.live.param.AudioParam
import com.frank.live.param.VideoParam
import org.json.JSONArray
import org.webrtc.EglBase
import org.webrtc.MediaStream

class LiveActivity : AppCompatActivity(),
        LiveStateChangeListener,OnNetworkChangeListener,View.OnClickListener {

    private var live_surface:SurfaceView?=null
    private lateinit var live_msg_edt:EditText
    private lateinit var live_send_btn:Button
    private lateinit var live_rv:RecyclerView
    private var livePusher: LivePusherNew? = null
    private var isPushing = false
    private var connectionReceiver: ConnectionReceiver? = null
    private var webRtcClient: WebRtcClient? = null
    private val hostUrl = "http://192.168.31.107:3000/"
    private val eglBase by lazy { EglBase.create() }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_live)
        initView()
        registerBroadcast(this)
        initPusher()
        startWebRTC()
    }

    private fun initView(){
        live_surface = findViewById(R.id.live_surface)
        live_msg_edt = findViewById(R.id.live_msg_edt)
        live_send_btn = findViewById(R.id.live_send_btn)
        live_rv = findViewById(R.id.live_rv)
        findViewById<Button>(R.id.live_start_btn).setOnClickListener(this)
        findViewById<Button>(R.id.live_stop_btn).setOnClickListener(this)
        live_send_btn.setOnClickListener(this)
    }

    private fun initPusher() {
        val width = 640//resolution
        val height = 480
        val videoBitRate = 800000//kb/s
        val videoFrameRate = 10//fps
        val videoParam = VideoParam(width, height,
                Integer.valueOf(Camera2Helper.CAMERA_ID_FRONT), videoBitRate, videoFrameRate)
        val sampleRate = 44100//sample rate: Hz
        val channelConfig = AudioFormat.CHANNEL_IN_STEREO
        val audioFormat = AudioFormat.ENCODING_PCM_16BIT
        val numChannels = 2//channel number
        val audioParam = AudioParam(sampleRate, channelConfig, audioFormat, numChannels)
        livePusher = LivePusherNew(this, videoParam, audioParam)
//        livePusher!!.switchCamera()
        livePusher!!.setPreviewDisplay(live_surface!!.holder)
    }

    private fun registerBroadcast(networkChangeListener: OnNetworkChangeListener) {
        connectionReceiver = ConnectionReceiver(networkChangeListener)
        val intentFilter = IntentFilter()
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
        registerReceiver(connectionReceiver, intentFilter)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (livePusher != null) {
            if (isPushing) {
                isPushing = false
                livePusher?.stopPush()
            }
            livePusher!!.release()
        }
        webRtcClient?.onDestroy()
        if (connectionReceiver != null) {
            unregisterReceiver(connectionReceiver)
        }
    }



    //直播出错
    override fun onError(msg: String?) {
        runOnUiThread(object :Runnable{
            override fun run() {
                Toast.makeText(LiveApplication.getInstance(),msg,Toast.LENGTH_SHORT).show()
            }
        })
    }

    //网络状态改变
    override fun onNetworkChange() {
        if (livePusher != null && isPushing) {
            livePusher?.stopPush()
            isPushing = false
        }
    }

    override fun onClick(v: View?) {
        var id = v!!.id
        when(id){
            R.id.live_start_btn->{
                livePusher!!.startPush(LiveConst.LIVE_URL,this)
                isPushing == true
            }
            R.id.live_stop_btn->{
                livePusher!!.stopPush()
                isPushing = false
            }
            R.id.live_send_btn->{

            }
        }
    }
    private fun startWebRTC() {

        webRtcClient = WebRtcClient(
                hostUrl,
                this.application,
                eglBase.eglBaseContext,
                object : WebRtcClient.RtcListener {
                    override fun onOnlineIdsChanged(jsonArray: JSONArray) {

                    }

                    override fun onCallReady(callId: String) {
                        runOnUiThread {
                            Toast.makeText(this@LiveActivity, "已连上服务器", Toast.LENGTH_SHORT).show()
                        }
                        webRtcClient?.speak()
                        webRtcClient?.startLocalAudioCapture(android.os.Build.MODEL)
                    }

                    override fun onStatusChanged(newStatus: String) {
                        runOnUiThread {
                            Toast.makeText(this@LiveActivity, newStatus, Toast.LENGTH_SHORT).show()
                        }
                    }

                    override fun onLocalStream(localStream: MediaStream) {
                    }

                    override fun onAddRemoteStream(remoteStream: MediaStream, endPoint: Int) {
                    }

                    override fun onRemoveRemoteStream(endPoint: Int) {
                    }
                })

    }

    override fun onPause() {
        super.onPause()
        webRtcClient?.onPause()
    }

    override fun onResume() {
        super.onResume()
        webRtcClient?.onResume()
    }

}